package com.hyg.base.ui.base;

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.hyg.base.R;
import com.hyg.base.listener.PermissionListener;
import com.hyg.base.view.BaseView;
import com.hyg.common.utils.ToastUtils;
import com.hyg.common.utils.language.LocalManageUtil;
import com.hyg.common.view.dialog.ConfirmDialog;
import com.hyg.common.view.dialog.DialogUtils;
import com.hyg.idea.utils.RxUtil;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

import io.reactivex.ObservableTransformer;


public abstract class BaseActivity<T extends BasePresenter> extends RxAppCompatActivity  implements BaseView {
    private static Activity mCurrentActivity;// 对所有activity进行管理
    public static List<Activity> mActivities = new LinkedList<Activity>();
    protected T mPresenter;
    private DialogUtils mDialogUtils;
    public PermissionListener mPermissionListener;

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(LocalManageUtil.setLocal(newBase));
    }

    @Override
    public void applyOverrideConfiguration(Configuration overrideConfiguration) {
        // 兼容androidX在部分手机切换语言失败问题
        if (overrideConfiguration != null) {
            int uiMode = overrideConfiguration.uiMode;
            overrideConfiguration.setTo(getBaseContext().getResources().getConfiguration());
            overrideConfiguration.uiMode = uiMode;
        }
        super.applyOverrideConfiguration(overrideConfiguration);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //初始化的时候将其添加到集合中
        synchronized (mActivities) {
            mActivities.add(this);
        }

        mPresenter = createPresenter();

        setContentView(provideContentViewId());

        bindButterKnife();

        init(savedInstanceState);
    }

    protected void showConfirmDialog(int stringResId) {
        showConfirmDialog(getString(stringResId));
    }

    protected void showConfirmDialog(String message) {
        new ConfirmDialog(this,message,getString(R.string.lib_sure),null,null).show();
    }

    protected void showToast(String msg) {
        ToastUtils.show(msg);
    }

    protected void showLoading(){
        showLoading("");
    }

    protected void showLoading(boolean cancelTouchOutside){
        showLoading("",cancelTouchOutside);
    }

    protected void showLoading(String msg){
        showLoading(msg,true);
    }

    protected void showLoading(String msg,boolean cancelTouchOutside){
        if(mDialogUtils == null){
            mDialogUtils = new DialogUtils();
        }
        mDialogUtils.showProgress(this,msg, cancelTouchOutside);
    }

    protected void hideLoading(){
        if(mDialogUtils != null){
            mDialogUtils.dismissProgress();
        }
    }

    protected void setVisibility(int resId, int visibility){
        View view = findViewById(resId);
        if(view != null){
            view.setVisibility(visibility);
        }
    }

    protected abstract @LayoutRes int provideContentViewId();

    protected void bindButterKnife(){}

    /**
     * 用于创建Presenter和判断是否使用MVP模式(由子类实现)
     */
    protected abstract T createPresenter();

    protected abstract void init(Bundle savedInstanceState);

    @Override
    public <T> ObservableTransformer<T, T> rxSchedulerHelper(boolean showLoading) {
        return RxUtil.rxSchedulerHelper(this, showLoading);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mCurrentActivity = this;
    }

    @Override
    protected void onPause() {
        super.onPause();
        mCurrentActivity = null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        //销毁的时候从集合中移除
        synchronized (mActivities) {
            mActivities.remove(this);
        }

        if (mPresenter != null) {
            mPresenter.detachView();
            mPresenter = null;
        }
    }

    /**
     * 退出应用的方法
     */
    public static void exitApp() {
        ListIterator<Activity> iterator = mActivities.listIterator();
        while (iterator.hasNext()) {
            Activity next = iterator.next();
            next.finish();
        }
    }

    public static Activity getCurrentActivity() {
        return mCurrentActivity;
    }

    /**
     * 统一退出控制
     */
//    private static long mPreTime;
//    @Override
//    public void onBackPressed() {
//        if (mCurrentActivity instanceof MainActivity){
//            //如果是主页面
//            if (System.currentTimeMillis() - mPreTime > 2000) {// 两次点击间隔大于2秒
//                ToastUtils.show("再按一次退出应用");
//                mPreTime = System.currentTimeMillis();
//                return;
//            }
//        }
//        super.onBackPressed();// finish()
//    }

    /**
     * 申请运行时权限
     */
    public void requestRuntimePermission(String[] permissions, PermissionListener permissionListener) {
        mPermissionListener = permissionListener;
        List<String> permissionList = new ArrayList<>();
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                permissionList.add(permission);
            }
        }

        if (!permissionList.isEmpty()) {
            ActivityCompat.requestPermissions(this, permissionList.toArray(new String[permissionList.size()]), 1);
        } else {
            permissionListener.onGranted();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 1:
                if (grantResults.length > 0) {
                    List<String> deniedPermissions = new ArrayList<>();
                    for (int i = 0; i < grantResults.length; i++) {
                        int grantResult = grantResults[i];
                        String permission = permissions[i];
                        if (grantResult != PackageManager.PERMISSION_GRANTED) {
                            deniedPermissions.add(permission);
                        }
                    }
                    if (deniedPermissions.isEmpty()) {
                        mPermissionListener.onGranted();
                    } else {
                        mPermissionListener.onDenied(deniedPermissions);
                    }
                }
                break;
        }
    }
}
